<?php
declare(strict_types=1);

namespace Zlf\Unit;


/**
 * Url处理工具
 * Class Arr
 * @package Core\Method
 */
class Url
{

    /**
     * 解析URL参数
     * @param string $url
     * @return array
     */
    public static function analysis(string $url): array
    {
        $url = trim($url);
        $info = Str::explode('?', $url);
        $uri = ['valid' => true, 'url' => $url, 'page' => $info[0], 'param' => []];
        if (substr($url, 0, 5) === 'https') {
            $uri['protocol'] = 'https';
        } elseif (substr($url, 0, 5) === 'http') {
            $uri['protocol'] = 'http';
        } else {
            $uri['valid'] = false;
        }
        if (isset($info[1]) && $info[1]) {
            parse_str(Str::explode('#', $info[1])[0], $param);
            $uri['param'] = $param ? $param : [];
        }
        return $uri;
    }

    /**
     * 追加URL参数
     * @param string $url
     * @param array $param
     * @return string
     * @author 竹林风@875384189 2021/3/28 15:34
     */
    public static function append(string $url, array $param): string
    {
        $info = self::analysis($url);
        $params = self::httpBuildQuery(array_merge($info['param'], $param));
        return $info['page'] . '?' . http_build_query($params);
    }

    /**
     * 组装URL
     * @param array $params
     * @return mixed
     * @author 竹林风@875384189 2022/6/2 10:00
     */
    public static function httpBuildQuery(array $params)
    {
        return Arr::removeEmptyElements($params);
    }


    /**
     * 获取URL中的参数
     * @param $url
     * @return array
     * @author 竹林风@875384189 2021/3/28 15:52
     */
    public static function params($url): array
    {
        $info = self::analysis($url);
        return $info['param'];
    }


    /**
     * 重置URL参数
     * @param string $url
     * @param array $params
     * @return string
     * @author 竹林风@875384189 2022/6/2 10:07
     */
    public static function reset(string $url, array $params = []): string
    {
        $info = self::analysis($url);
        $params = self::httpBuildQuery($params);
        return $info['page'] . '?' . http_build_query($params);
    }
}

